package com.jiubanqingchen.wish.interceptors;

import com.jfinal.aop.Aop;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jiubanqingchen.wish.framework.annotation.AuthorityKey;
import com.jiubanqingchen.wish.framework.base.controller.BaseController;
import com.jiubanqingchen.wish.framework.base.user.IUser;
import com.jiubanqingchen.wish.framework.enums.SystemStatus;
import com.jiubanqingchen.wish.framework.exception.WishException;
import com.jiubanqingchen.wish.framework.exception.WishExceptionKey;
import com.jiubanqingchen.wish.framework.security.AuthService;

/**
 * 权限拦截器
 *
 * @author light_dust
 * @since 2021/4/30 15:30
 */
public class AuthorityInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation inv) {
        BaseController controller = (BaseController) inv.getController();
            IUser user = controller.getCurrentUser();
            if (user == null) {
                controller.renderJson(SystemStatus.LOGOUT);
                return;
            }
            if (!controller.getClass().isAnnotationPresent(AuthorityKey.class)) {
                throw new WishException(WishExceptionKey.AUTHORITY_CONTROLLER_NOT_AUTHORITY_kEY);
            }

            String controllerKey = controller.getClass().getAnnotation(AuthorityKey.class).value();
            AuthorityKey authorityKey = inv.getMethod().getAnnotation(AuthorityKey.class);
            if (authorityKey == null) {
                throw new WishException(WishExceptionKey.AUTHORITY_METHOD_NOT_AUTHORITY_kEY);
            }
            String methodKey = authorityKey.value();

            boolean flag = Aop.get(AuthService.class).judgeAuthority(user.getUserId(), controllerKey + ":" + methodKey);
            if (!flag) {
                throw new WishException(WishExceptionKey.AUTHORITY_USER_NOT_ALLOWED);
            }
        inv.invoke();
    }
}
